<script setup>
import { ref, onMounted } from 'vue'
import { listFriend } from '@/api/user'
import { message } from '@/api/chat'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'

const router = useRouter()
const friends = ref([])
const chatMessages = ref([])
const loading = ref(false)

// 获取好友列表
const getFriends = async () => {
  try {
    const res = await listFriend()
    friends.value = res.data
    // 获取每个好友的最后一条消息
    await getLastMessages()
  } catch (error) {
    showToast('获取好友列表失败')
  }
}

// 获取与每个好友的最后一条消息
const getLastMessages = async () => {
  try {
    loading.value = true
    const messagePromises = friends.value.map(friend => message(friend.id))
    const results = await Promise.all(messagePromises)
    
    chatMessages.value = results.map((res, index) => {
      const messages = res.data?.message || []
      return {
        friend: friends.value[index],
        lastMessage: messages[messages.length - 1] || null
      }
    }).filter(item => item.lastMessage)
  } catch (error) {
    showToast('获取消息记录失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getFriends()
})
</script>

<template>
  <div class="message-page">
    <van-nav-bar title="消息" />
    
    <!-- 好友列表 -->
    <div class="friends-scroll">
      <div class="friends-list">
        <div 
          v-for="friend in friends" 
          :key="friend.id"
          class="friend-item"
          @click="router.push(`/chat/${friend.id}`)"
        >
          <img :src="friend.avatar" class="avatar" />
          <div class="name">{{ friend.username }}</div>
        </div>
      </div>
    </div>

    <!-- 消息通知 -->
    <van-cell-group class="notice-section">
      <van-cell 
        title="消息通知" 
        is-link 
        center
        icon="bell"
      >
        <template #right-icon>
          <van-badge :content="3" />
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 聊天列表 -->
    <div class="chat-list">
      <van-skeleton title avatar :row="3" :loading="loading" v-if="loading" />
      <template v-else>
        <van-cell-group v-if="chatMessages.length > 0">
          <van-cell 
            v-for="chat in chatMessages" 
            :key="chat.friend.id"
            center
            clickable
            @click="router.push(`/chat/${chat.friend.id}`)"
          >
            <template #icon>
              <img :src="chat.friend.avatar" class="chat-avatar" />
            </template>
            <template #title>
              <div class="chat-info">
                <span class="username">{{ chat.friend.username }}</span>
                <span class="time">{{ new Date(chat.lastMessage.createTime).toLocaleTimeString() }}</span>
              </div>
              <div class="last-message">{{ chat.lastMessage.content }}</div>
            </template>
          </van-cell>
        </van-cell-group>
        <van-empty v-else description="暂无聊天记录" />
      </template>
    </div>
  </div>
</template>

<style scoped lang="scss">
.message-page {
  min-height: 100vh;
  background: #f7f7f7;

  .friends-scroll {
    background: #fff;
    padding: 12px 0;
    margin-bottom: 12px;
    overflow-x: auto;
    
    .friends-list {
      display: flex;
      padding: 0 12px;
      
      .friend-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 20px;
        min-width: 60px;
        
        .avatar {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          margin-bottom: 8px;
        }
        
        .name {
          font-size: 12px;
          color: #333;
          width: 100%;
          text-align: center;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }

  .notice-section {
    margin-bottom: 12px;
  }

  .chat-list {
    .chat-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      margin-right: 12px;
    }

    .chat-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 4px;

      .username {
        font-weight: 500;
        color: #333;
      }

      .time {
        font-size: 12px;
        color: #999;
      }
    }

    .last-message {
      font-size: 13px;
      color: #666;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>